<template>
  <view class="content">
    <view class="login-box">
      <view class="login-head">
        <view class="login-tx">
          <open-data type="userAvatarUrl"></open-data>
        </view>
      </view>
      <view class="login-main">
        <view class="login-h4">申请获取以下权限</view>
        <view class="login-txt">获取你的公开信息（昵称、头像等）</view>
        <button class="login-btn" open-type="getUserInfo" @getuserinfo="getUserInfo ">授权登录</button>
        <button class="login-btn" open-type="getUserInfo" @getuserinfo="getUserInfo1 ">拒绝</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {};
  },
  onLoad: function() {},

  methods: {
    getUserInfo: function() {
      uni.showModal({
        title: "温馨提示",
        content: "授权微信登录后才能正常使用小程序功能",
        success(res) {
          //如果用户点击了确定按钮
          if (res.confirm) {
            uni.getUserProfile({
              desc: "获取你的昵称、头像、地区及性别",
              success: res => {
                console.log(res);

                uni.request({
                  url: getApp().globalData.http + "/user/update",
                  data: {
                    nickname: res.userInfo.nickName,
                    avatar_url: res.userInfo.avatarUrl
                  },
                  method: "post",
                  header: {
                    "content-type": "application/x-www-form-urlencoded",
                    token: uni.getStorageSync("token")
                  },
                  success: data => {
                    uni.request({
                      url: getApp().globalData.http + "/user/info",
                      data: "",
                      method: "post",
                      header: {
                        "content-type": "application/x-www-form-urlencoded",
                        token: uni.getStorageSync("token")
                      },
                      success: res => {
                        uni.setStorageSync("user", res.data.data);
                        wx.navigateBack({
                          delta: 1
                        });
                      }
                    });
                  }
                });
              },
              fail: res => {
                //拒绝授权
                uni.showToast({
                  title: "您拒绝了请求,不能正常使用小程序",
                  icon: "error",
                  duration: 2000
                });
                return;
              }
            });
          } else if (res.cancel) {
            //如果用户点击了取消按钮
            uni.showToast({
              title: "您拒绝了请求,不能正常使用小程序",
              icon: "error",
              duration: 2000
            });
            return;
          }
        }
      });
    },
    getUserInfo1: function() {
      wx.navigateBack({
        delta: 1
      });
    }
  }
};
</script>
